//
//  MainChatController.m
//  BaiYing_Thinker
//
//  Created by 鹏 朱 on 15/10/24.
//  Copyright (c) 2015年 XKJH. All rights reserved.
//

#import "MainChatController.h"
#import "MainChatView.h"
#import "FileMangeHelper.h"
#import "ZipArchive.h"
#import "zlib.h"
#import "zconf.h"
#import "XKO_CreateUIViewHelper.h"
#import "AppDelegate.h"
#import "FileDownload.h"
#import "FileMangeHelper.h"
#import "DatabaseCache.h"
#import "SubjectMessage.h"
#import "SessonContentMessage.h"
#import "SubjectMessage.h"
#import "SessionMessage.h"
#import "PluginComponentController.h"

@interface MainChatController(P)

-(NSString*)getPath:(NSString*)name;

@end

@interface MainChatController ()

@property(nonatomic, strong) UIButton *newMessageBtn;
@property(nonatomic, strong) PluginComponentController *pluginComponent;
@property(nonatomic, strong) NSIndexPath *messageIndexPath;

@end

@implementation MainChatController

#pragma mark - View lifecycle

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self initDataSource];
    [self initInfo];
    
}

- (BOOL)prefersStatusBarHidden {
    return YES;
}

- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];
    
}

#pragma mark - private methord

-(NSString*)getPath:(NSString*)name {
    return [[[NSBundle mainBundle] resourcePath] stringByAppendingFormat:@"/Res/%@.png",name];
}

- (void)initInfo {
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(receiveNewMessage:)
                   name:kNotificationReceiveNewMessage
                 object:nil];
    
    [center addObserver:self selector:@selector(goNext:)
                   name:@"KGoNextNotification"
                 object:nil];
}

- (NSIndexPath *)curIndexPath {
    
    _curIndexPath = [self.sv getCurIndexPath];
    
    return _curIndexPath;
    
}

- (void)initDataSource {
    
    NSMutableArray *sessionContentList = [[DatabaseCache shareInstance] selectDataSource];
    
    MainChatView* sv =[MainChatView createWithFrame:self.view.bounds ds:sessionContentList];
    self.sv = sv;
    [self.view addSubview:self.sv];

    if (sessionContentList.count <= 0) {
        [self createNewSubject:YES];
    } else {
        [self.sv reloadData];
        
        NSMutableArray *sessions = [kAppDelegate.sessionContentList lastObject];
        [self.sv setCurIndexPath:[NSIndexPath indexPathForRow:sessions.count - 1 inSection:kAppDelegate.sessionContentList.count - 1] openAnimator:NO];
    }
}

- (void)receiveNewMessage:(NSNotification *)notification {

    NSDictionary *messageDic = notification.userInfo;
    SessonContentMessage *message = [messageDic objectForKey:KMessageParameter];

    //收到问题，回复或者讨论的时候显示该button
    if ([message.isMyself isEqual:@0] && ![message.model isEqualToString:@"SYSTEM"]) {
    
        
        if (([message.model isEqualToString:@"ANSWER"] || [message.model isEqualToString:@"TALK"]) && IsEmpty(message.recevier)) {
            
        } else {
            [self.newMessageBtn setTitle:message.msg_content forState:UIControlStateNormal];
            if (!self.newMessageBtn.superview) {
                [kCurrentKeyWindow addSubview:self.newMessageBtn];
            }
        }
    } else if (![message.sys_code isEqualToString:@"1006"]) {
        
        [self.newMessageBtn setTitle:message.msg_content forState:UIControlStateNormal];
        if (!self.newMessageBtn.superview) {
            [kCurrentKeyWindow addSubview:self.newMessageBtn];
        }
    }
    
    //判断收到的消息是不是新的主题
    NSPredicate *predicateSubject = [NSPredicate predicateWithFormat:@"subject_id == %@",message.subject_id];
    NSArray *filteredSubject = [Util findObjectFromArrary:kAppDelegate.subjectList predicate:predicateSubject];
    if (filteredSubject) {
        
        SubjectMessage *subjectMessage = filteredSubject[0];
        NSUInteger section = [kAppDelegate.subjectList indexOfObject:subjectMessage];
        
        //判断收到的消息是不是新的session
        NSPredicate *predicateSession = [NSPredicate predicateWithFormat:@"subject_id == %@ and session_id == %@",message.subject_id,message.session_id];
        NSArray *filteredSession = [Util findObjectFromArrary:kAppDelegate.sessionList predicate:predicateSession];
        if (filteredSession) {
            
            SessionMessage *sessionMessage = filteredSession[0];
            
            NSArray *filteredSession2 = [Util findObjectFromArrary:kAppDelegate.sessionList predicate:predicateSubject];
            NSUInteger row = [filteredSession2 indexOfObject:sessionMessage];

            [[[kAppDelegate.sessionContentList objectAtIndex:section] objectAtIndex:row] addObject:message];
            self.sv.dataSource = kAppDelegate.sessionContentList;
            
            _messageIndexPath = [NSIndexPath indexPathForRow:row inSection:section];
            [self.sv reloadDataAtIndexPath:_messageIndexPath];
            
            if (self.curIndexPath.section == section && self.curIndexPath.row == row) {
                
                self.sv.isScrollToBottom = YES;
                [self.sv setCurIndexPath:_messageIndexPath openAnimator:YES];
                self.sv.isScrollToBottom = NO;
                
            }
            
        } else {
            
            //设置主题内容
            message.subject_content = subjectMessage.content;
            
            //更新数据源
            [[kAppDelegate.sessionContentList objectAtIndex:section] addObject:[NSMutableArray arrayWithObject:message]];
            self.sv.dataSource = kAppDelegate.sessionContentList;
            
            //更新session
            SessionMessage *sessionMessage = [[SessionMessage alloc] initWithSessonContentMessage:message];
            [kAppDelegate.sessionList addObject:sessionMessage];
            
            //刷新列表
            NSMutableArray *sessions = [kAppDelegate.sessionContentList objectAtIndex:section];
            _messageIndexPath = [NSIndexPath indexPathForRow:sessions.count - 1 inSection:section];
            [self.sv reloadDataAtIndex:section];
            
        }
        
    } else {
        
        [self reloadData];
        _messageIndexPath = [NSIndexPath indexPathForRow:0 inSection:kAppDelegate.sessionContentList.count - 1];
    }
}

- (UIButton *)newMessageBtn {
    
    if (!_newMessageBtn) {
        
        UIButton *messageBtn = [XKO_CreateUIViewHelper createUIButtonWithFrame:CGRectMake(kScreenWidth - 100, 30, 80, 35) title:@"新的消息" titleColor:[UIColor whiteColor] titleFont:kFontSize14 backgroundColor:nil hasRadius:YES targetSelector:@selector(showNewMessage:) target:self];
        [messageBtn setBackgroundImage:IMAGE(@"dialogbox") forState:UIControlStateNormal];

        _newMessageBtn = messageBtn;
        
    }
    return _newMessageBtn;
}

- (void)showNewMessage:(UIButton *)sender {
    
    [sender removeFromSuperview];

    self.sv.isScrollToBottom = YES;
    [self.sv setCurIndexPath:_messageIndexPath openAnimator:NO];
    self.sv.isScrollToBottom = NO;

}

/**
 *  收到新消息
 *
 *  @param notification 通知参数
 */
- (void)goNext:(NSNotification *)notification {

    NSString *direction = [notification.userInfo objectForKey:@"KDirection"];
    NSIndexPath *indexPath = self.curIndexPath;
    NSInteger row = indexPath.row;
    
    //KDiretionDown:下拉; KDiretionUp:上拉;
    if ([direction isEqualToString:@"KDiretionDown"]) {
        
        if (indexPath.section > 0) {
            
            NSUInteger sectionCount = [(NSMutableArray *)[kAppDelegate.sessionContentList objectAtIndex:indexPath.section - 1] count];
            if (indexPath.row >= sectionCount) {
                row = sectionCount - 1;
            }
            
            [self.sv setCurIndexPath:[NSIndexPath indexPathForRow:row inSection:indexPath.section - 1] openAnimator:NO];
            
        }
        
    } else if ([direction isEqualToString:@"KDiretionUp"]){
        
        if (indexPath.section < kAppDelegate.sessionContentList.count - 1) {
            
            NSUInteger sectionCount = [(NSMutableArray *)[kAppDelegate.sessionContentList objectAtIndex:indexPath.section + 1] count];
            if (indexPath.row >= sectionCount) {
                row = sectionCount - 1;
            }
            
            [self.sv setCurIndexPath:[NSIndexPath indexPathForRow:row inSection:indexPath.section + 1] openAnimator:NO];
            
        } else {
            
            if ([[notification.userInfo objectForKey:@"isNodata"] isEqual:@0]) {
                [self createNewSubject:NO];
            }
        }
    }
}

- (void)reloadData {
    
    [self addLocalData];
    [self.sv reloadData];
    
//        NSMutableArray *newSubject = [[NSMutableArray alloc] initWithObjects:[[NSMutableArray alloc] initWithObjects:message, nil], nil];
//        [self.dataSource addObject:newSubject];
//        self.sv.dataSource = self.dataSource;
//
//        SubjectMessage *subjectMessage = [[SubjectMessage alloc] initWithSessonContentMessage:message];
//        [kAppDelegate.subjectList addObject:subjectMessage];
//
//        SessionMessage *sessionMessage = [[SessionMessage alloc] initWithSessonContentMessage:message];
//        [kAppDelegate.sessionList addObject:sessionMessage];
}

/**
 *  本地数据更新
 */
- (void)addLocalData {
    
    NSMutableArray *sessionList = [[DatabaseCache shareInstance] selectDataSource];
    self.sv.dataSource = sessionList;
    
}

/**
 *  当滑到最后一个主题时就显示：请问有什么可以帮您的？
 *
 *  @param isFirstLunch 是否是第一次启动
 */
- (void)createNewSubject:(BOOL)isFirstLunch{
    
    //开启新的话题
    NSDictionary *dic = @{@"clientid":@"BAIYING_WORKER01_CLIENT",@"content":@{@"sys_code":@"9999",@"text":@"请问有什么可以帮您的？",@"type":@"TEXT"},@"model":@"SYSTEM",@"msg_id":kAppDelegate.messageId};
    SessonContentMessage *message = [[SessonContentMessage alloc] initWithDictionary:dic isMyself:@1];
    
    NSMutableArray *newSubject = [[NSMutableArray alloc] initWithObjects:[[NSMutableArray alloc] initWithObjects:message, nil], nil];
    
    [kAppDelegate.sessionContentList addObject:newSubject];
    self.sv.dataSource = kAppDelegate.sessionContentList;
    [self.sv reloadData];

    if (isFirstLunch) {
        
        //第一次启动不需要动画效果
        [self.sv setCurIndexPath:[NSIndexPath indexPathForRow:0 inSection:kAppDelegate.sessionContentList.count - 1] openAnimator:NO];
        
    } else {
        
        [self.sv setCurIndexPath:[NSIndexPath indexPathForRow:0 inSection:kAppDelegate.sessionContentList.count - 1] openAnimator:NO];
    }
}

@end
